package com.parleys.android.client.ui;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.parleys.android.client.R;
import com.parleys.android.client.provider.ParleysContract.Channels;
import com.parleys.android.client.provider.ParleysContract.Presentations;
import com.parleys.android.client.service.ParleysService;
import com.parleys.android.client.service.ParleysServiceHelper;
import com.parleys.android.client.util.DetachableResultReceiver;
import com.parleys.android.client.util.DetachableResultReceiver.Receiver;
import com.parleys.android.client.util.NotifyingAsyncQueryHandler;
import com.parleys.android.client.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import com.parleys.android.client.util.ParleysUriUtils;
import com.parleys.android.client.util.UIUtils;

public class PresentationsActivity extends ListActivity implements AsyncQueryListener, Receiver {

	private static final String TAG = "PresentationsActivity";
	
    private State mState;

    private static ParleysServiceHelper parleysServiceHelper = ParleysServiceHelper.getInstance();
    private Uri mPresentationsUri;
	private NotifyingAsyncQueryHandler mHandler;
    private PresentationsAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_presentations);

        mState = (State) getLastNonConfigurationInstance();
        final boolean previousState = mState != null;

        mPresentationsUri = this.getIntent().getData();

        mAdapter = new PresentationsAdapter(this);
        setListAdapter(mAdapter);

        mHandler = new NotifyingAsyncQueryHandler(this, this);
        startQuery();

        if (previousState) {
            mState.mReceiver.setReceiver(this);
            updateRefreshStatus();
        } else {
            mState = new State();
            mState.mReceiver.setReceiver(this);
            parleysServiceHelper.getPresentations(this, Channels.getChannelId(mPresentationsUri), mState.mReceiver);
        }
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		final Window window = getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}
	
	@Override
    public Object onRetainNonConfigurationInstance() {
        mState.mReceiver.clearReceiver();
        return mState;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		cursor.setNotificationUri(getContentResolver(), mPresentationsUri);
		startManagingCursor(cursor);
		mAdapter.changeCursor(cursor);
	}

	public void onHomeClick(View v) {
		UIUtils.goHome(this);
	}
	
    @Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
        final Cursor cursor = (Cursor) mAdapter.getItem(position);
        final int presentationId = cursor.getInt(PresentationsQuery.PRESENTATION_ID);
        final Uri channelUri = Channels.buildChannelUri(presentationId);
        final Intent intent = new Intent(Intent.ACTION_VIEW, channelUri);
        intent.putExtra(Intent.EXTRA_TITLE, cursor.getString(PresentationsQuery.TITLE));
        startActivity(intent);
	}

	private void startQuery() {
    	mHandler.cancelOperation(PresentationsQuery.TOKEN);
        mHandler.startQuery(PresentationsQuery.TOKEN, null, mPresentationsUri, PresentationsQuery.PROJECTION, null, null, PresentationsQuery.SORT);
    }
    
    private void updateRefreshStatus() {
        findViewById(R.id.refresh_presentations_separator).setVisibility(mState.mSyncing ? View.VISIBLE : View.GONE);
        findViewById(R.id.refresh_presentations_progress).setVisibility(mState.mSyncing ? View.VISIBLE : View.GONE);
    }
    
    /** {@inheritDoc} */
    public void onReceiveResult(int resultCode, Bundle resultData) {
        switch (resultCode) {
            case ParleysService.STATUS_RUNNING: {
                mState.mSyncing = true;
                updateRefreshStatus();
                break;
            }
            case ParleysService.STATUS_FINISHED: {
                mState.mSyncing = false;
                updateRefreshStatus();
                break;
            }
            case ParleysService.STATUS_ERROR: {
                mState.mSyncing = false;
                updateRefreshStatus();
                break;
            }
        }
    }

    public static final class PresentationsItemViews {
    	ImageView thumbnailView;
        TextView titleView;
    }

    private class PresentationsAdapter extends CursorAdapter {
    	
		public PresentationsAdapter(Context context) {
			super(context, null);
		}

	    protected void findAndCacheViews(View view) {
	    	PresentationsItemViews views = new PresentationsItemViews();
	    	views.thumbnailView = (ImageView) view.findViewById(R.id.presentations_thumbnail);
	        views.titleView = (TextView) view.findViewById(R.id.presentations_title);
	        view.setTag(views);
	    }

	    @Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View v = getLayoutInflater().inflate(R.layout.list_item_presentations, parent, false);
            findAndCacheViews(v);
            return v;
		}
    	
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			PresentationsItemViews views = (PresentationsItemViews) view.getTag();
			
			final String presentationId = cursor.getString(PresentationsQuery.PRESENTATION_ID);
			final String name = cursor.getString(PresentationsQuery.TITLE);
			final String thumbnailUrl = cursor.isNull(PresentationsQuery.THUMBNAIL_URL) ? null : ParleysUriUtils.buildPresentationThumbnailUri(presentationId, cursor.getString(PresentationsQuery.THUMBNAIL_URL));
			
            views.titleView.setText(name);
            
	        parleysServiceHelper.downloadImage(thumbnailUrl, views.thumbnailView);
		}

    }
    
    private static class State {
        public DetachableResultReceiver mReceiver;
        public boolean mSyncing = false;

        private State() {
            mReceiver = new DetachableResultReceiver(new Handler());
        }

    }

    private interface PresentationsQuery {
    	int TOKEN = 0x01;
    	
        String[] PROJECTION = {
                BaseColumns._ID,
                Presentations.PRESENTATION_ID,
                Presentations.TITLE,
                Presentations.SUMMARY,
                Presentations.THUMBNAIL_URL,
        };
        
        String SORT = Presentations.DEFAULT_SORT;

        int _ID 				= 0;
        int PRESENTATION_ID 			= 1;
        int TITLE				= 2;
        int SUMMARY			= 3;
	    int THUMBNAIL_URL		= 4;			
    }
}
